package com.springapi.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@RestController
@RequestMapping("/api/file")
@CrossOrigin(origins = "*",maxAge = 3600)
public class FileController {

    @Value("${filesavepath}")
    private String FILE_SAVE_PATH;


    // 生成6位随机数的方法
    private static String generateRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            char c = chars.charAt(random.nextInt(chars.length()));
            sb.append(c);
        }
        return sb.toString();
    }

    //http://localhost:8081/api/file/uploadFile
    @PostMapping("/uploadFile")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {

        System.out.println("触发文件上传接口");

        if (file.isEmpty()) {
            return new ResponseEntity<>("请上传文件", HttpStatus.BAD_REQUEST);
        }

        // 获取原始文件名和扩展名
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        int dotIndex = originalFilename.lastIndexOf(".");
        if (dotIndex != -1) {
            extension = originalFilename.substring(dotIndex);
        }

        // 生成新的文件名：时间戳+6位随机数+扩展名
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String randomString = generateRandomString(6);
        String newFileName = timestamp + "_" + randomString + extension;

        try {
            System.out.println("开始上传文件，文件保存地址FILE_SAVE_PATH:"+FILE_SAVE_PATH);
            // 创建保存文件的目录（如果不存在）
            Path filePath = Paths.get(FILE_SAVE_PATH, newFileName);
            Files.createDirectories(filePath.getParent());

            // 将文件保存到指定路径
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件上传成功，文件名称："+newFileName);
            // 返回新文件名作为响应
            return new ResponseEntity<>(newFileName, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("", HttpStatus.OK);
        }
    }
}
